package com.toymate.common.exception;

import com.toymate.common.enums.ErrorEnum;
import com.toymate.common.web.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * 全局异常处理
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 自定义业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<?> handleBusinessException(BusinessException e) {
        log.error("系统异常 {}", e.getMessage());
        return Result.error(ErrorEnum.ERROR.getCode(), e.getMessage());
    }

    /**
     * 处理所有不可知异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result<?> handleException(Exception e) {
        log.error("系统异常 {}", e.getMessage());
        return Result.error(ErrorEnum.SYSTEM_ERROR.getCode(), e.getMessage());
    }

    /**
     * 拦截断言异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public Result<Object> handleIllegalArgumentException(IllegalArgumentException e) {
        int code = ErrorEnum.ASSERT_ARGUMENT_ERROR.getCode();
        String msg = Objects.requireNonNull(e.getMessage());
        return Result.error(code, msg);
    }

}
